package com.itheima.dao.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl implements AccountDao {

    //交给ioc容器管理
    private QueryRunner queryRunner;

    //依赖注入
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }


    public void save(Account account) {
        try {
            queryRunner.update("insert into account values(null,?,?)", account.getName(), account.getBalance());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void delete(String name) {
        try {
            queryRunner.update("delete from account where name = ?",name);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updata(Account account) {
        try {
            queryRunner.update("update account set balance =? where name = ? ",account.getBalance(),account.getName());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Account findByName(String name) {
        try {
            return queryRunner.query("select * from account where name = ? ",new BeanHandler<Account>(Account.class),name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //查询全部
    public List<Account> findAll() {
        try {
            return queryRunner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
